﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Store;

namespace EShop.Services.Store
{
    public class DimensionService : IDimensionService
    {
        #region Constants
        private const string DIMENSION_BY_ID_KEY = "Dimension.id-{0}";
        private const string DIMENSION_PATTERN_KEY = "Dimension";
        #endregion

        #region Fields
        private readonly IRepository<Dimension> _dimensionRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public DimensionService(IRepository<Dimension> dimensionRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _dimensionRepository = dimensionRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
        #endregion

        public Dimension GetDimensionById(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            //格式化缓存条件
            string key = string.Format(DIMENSION_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var dimension = _dimensionRepository.GetById(id);
                return dimension;
            });
        }

        public bool AddDimension(Dimension model)
        {

            if (model == null) throw new ExtException("NUll Dimension Model");

            int rs = _dimensionRepository.Insert(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs > 0 ? true : false;
        }

        public bool UpdateDimension(Dimension model)
        {
            if (model == null) throw new ExtException("NUll Dimension Model");

            int rs = _dimensionRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs > 0 ? true : false;
        }

        public bool DelDimension(string id)
        {
            throw new NotImplementedException();
        }

        public IList<Dimension> GetAllDimension()
        {
            var dimension = _dimensionRepository.Table.ToList();
            return dimension;
        }
    }
}
